package cn.z2huo.knowledge.concurrency.callable.completablefuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author z2huo
 */
class CompletableFutureTest {

    static class MyTask {
        private final int id;

        public MyTask(int id) {
            this.id = id;
        }

        public String process() {
            try {
                TimeUnit.SECONDS.sleep(10 - id);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "result is " + id;
        }
    }

    public static Future<String> process(int i) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> new MyTask(i).process());
        return future;
    }

    public static void main(String[] args) {
        List<Future<String>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            results.add(process(i));
        }
        for (Future<String> result : results) {
            try {
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
